#include <soar.h>

struct node
{/*{{{*/
    unsigned int quit;
    char *msg;
    struct listp_link link;
};/*}}}*/

struct thrd_ctl
{/*{{{*/
    unsigned long thrd_id;
    THRD_MSGQ queue;
};/*}}}*/

void thrd_func(struct thrd_ctl *thrd_ctl)
{/*{{{*/
    int res;
    unsigned int quit=0;
    struct listp_link list;
    struct node *node;

    while(!quit)
    {
        //if((res=thrd_msgq_recv(thrd_ctl->queue, -1, &list)))
        if((res=thrd_msgq_recv(thrd_ctl->queue, &list, 10*1000)))
        {
            printf("thrd: res:%d\n", res);
            continue;
        }
        while(!listp_is_empty(&list))
        {
            node=listp_entry(list.next, struct node, link);
            printf("thrd: %s\n", node->msg?node->msg:"空");
            listp_del(&node->link);
            quit=node->quit;
            free(node->msg);
            free(node);
        }
    }
}/*}}}*/

int main()
{/*{{{*/
    struct thrd_ctl thrd_ctl;    
    char *msg_in;
    int msg_in_size;
    char *ptr;
    struct node *node;

    ALLOC_MULTI_RETERR(msg_in, char, MSG_SIZE, -1);

    if(thrd_msgq_create(&thrd_ctl.queue))
    {
        printf("thrd_msgq创建出错\n");
        return(-1);
    }
    if(thrd_create((THRD_FUNC_T)thrd_func, (void *)&thrd_ctl,
                THRD_DETACH, &thrd_ctl.thrd_id))
    {
        printf("线程创建出错\n");
        return(-1);
    }

    while(fgets(msg_in, MSG_SIZE, stdin))
    {
        if((ptr=strchr(msg_in, RTN)))  *ptr=ZERO;
        if((msg_in_size=strlen((char *)msg_in)) == 0)
            break;
        ALLOC(node, struct node, GO_OUT);
        ALLOC_MULTI(node->msg, char, msg_in_size+1, GO_OUT);
        node->quit=0;
        strcpy(node->msg, msg_in);
        if(thrd_msgq_send(thrd_ctl.queue, &node->link))
            goto GO_OUT;
    }

    ALLOC(node, struct node, GO_OUT);
    ALLOC_MULTI(node->msg, char, msg_in_size+1, GO_OUT);
    node->quit=1;
    node->msg=NULL;
    thrd_msgq_send(thrd_ctl.queue, &node->link);
    printf("退出\n");
    sleep(2);

GO_OUT:
    thrd_msgq_destroy(thrd_ctl.queue);
    return(0);
}/*}}}*/
